package cn.tedu.myvrd.controller;

import cn.tedu.myvrd.entity.Banner;
import cn.tedu.myvrd.mapper.BannerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@RestController
public class BannerController {

    @Autowired(required = false)
    BannerMapper mapper;

    @RequestMapping("/bannerlist")
    public List<Banner> list(){
        return mapper.selectAll();
    }

    @RequestMapping("/deletebanner")
    public void deleteById(int id){
        Banner banner = mapper.selectById(id);
        //得到图片路径
        String path = "D:/upload"+banner.getImgurl();
        new File(path).delete(); //删除文件
        mapper.deleteById(id);
    }

    @RequestMapping("/uploadbanner")
    public void upload(MultipartFile file){
        //得到文件名
        String fileName = file.getOriginalFilename();
        //得到文件后缀名
        String suffix = fileName.substring(fileName.indexOf("."));
        //得到唯一文件名
        fileName = UUID.randomUUID()+suffix;
        //保存文件到D盘下
        try {
            file.transferTo(new File("D:/upload/"+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Banner banner = new Banner(); //创建实体对象
        banner.setImgurl("/"+fileName); //把路径封装到对象中
        mapper.insert(banner);
    }
}
